'use client';

import Link from 'next/link';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import PuzzleCaptcha from '@/components/ui/puzzle-captcha';

export default function ResetPasswordPage() {
  const router = useRouter();
  const [email, setEmail] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [captchaVerified, setCaptchaVerified] = useState(false);
  const [showCaptcha, setShowCaptcha] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!captchaVerified) {
      setShowCaptcha(true);
      return;
    }
    
    setIsLoading(true);
    setError('');
    setSuccess(false);

    try {
      const response = await fetch('/api/auth/reset-password', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ email })
      });
      
      const data = await response.json();
      
      if (data.success) {
        setSuccess(true);
        
        // 如果发送成功，重定向到验证码页面
        setTimeout(() => {
          router.push(`/auth/reset-password/confirm?email=${encodeURIComponent(email)}`);
        }, 2000);
      } else {
        throw new Error(data.message || '发送重置密码邮件失败');
      }
    } catch (err: any) {
      setError(err.message || '发送重置密码邮件失败，请稍后重试');
    } finally {
      setIsLoading(false);
    }
  };

  const handleCaptchaSuccess = () => {
    setCaptchaVerified(true);
    setTimeout(() => setShowCaptcha(false), 500);
  };

  const handleCaptchaClose = () => {
    setShowCaptcha(false);
  };

  const handleStartVerification = () => {
    if (!email) {
      setError('请输入邮箱地址');
      return;
    }
    
    if (!email.includes('@')) {
      setError('请输入有效的邮箱地址');
      return;
    }
    
    setError('');
    setShowCaptcha(true);
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="flex min-h-screen flex-1 flex-col justify-center px-6 py-12 lg:px-8">
        <div className="sm:mx-auto sm:w-full sm:max-w-sm">
          <h2 className="mt-10 text-center text-2xl font-bold leading-9 tracking-tight text-gray-900">
            重置密码
          </h2>
        </div>

        <div className="mt-10 sm:mx-auto sm:w-full sm:max-w-sm">
          {error && (
            <div className="mb-4 p-3 text-sm text-red-700 bg-red-100 rounded-md">
              {error}
            </div>
          )}
          
          {success ? (
            <div className="mb-4 p-3 text-sm text-green-700 bg-green-100 rounded-md">
              <p>验证码已发送到您的邮箱，请查收并完成后续步骤。</p>
              <p>正在跳转到验证码输入页面...</p>
            </div>
          ) : (
            <form className="space-y-6" onSubmit={handleSubmit}>
              <div>
                <label htmlFor="email" className="block text-sm font-medium leading-6 text-gray-900">
                  邮箱地址
                </label>
                <div className="mt-2">
                  <input
                    id="email"
                    name="email"
                    type="email"
                    autoComplete="email"
                    required
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6"
                  />
                </div>
              </div>

              {captchaVerified && (
                <div className="flex items-center">
                  <div className="flex-shrink-0">
                    <svg className="h-5 w-5 text-green-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                      <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                    </svg>
                  </div>
                  <span className="ml-2 text-sm text-green-600">验证成功</span>
                </div>
              )}

              <div>
                {captchaVerified ? (
                  <button
                    type="submit"
                    disabled={isLoading || !email}
                    className="flex w-full justify-center rounded-md bg-blue-600 px-3 py-1.5 text-sm font-semibold leading-6 text-white shadow-sm hover:bg-blue-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {isLoading ? '发送中...' : '发送验证码'}
                  </button>
                ) : (
                  <button
                    type="button"
                    onClick={handleStartVerification}
                    disabled={!email}
                    className="flex w-full justify-center rounded-md bg-blue-600 px-3 py-1.5 text-sm font-semibold leading-6 text-white shadow-sm hover:bg-blue-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    安全验证
                  </button>
                )}
              </div>
            </form>
          )}

          <p className="mt-10 text-center text-sm text-gray-500">
            记起密码了?{' '}
            <Link href="/auth/login" className="font-semibold leading-6 text-blue-600 hover:text-blue-500">
              返回登录
            </Link>
          </p>
        </div>
      </div>
      
      {/* 拼图验证码弹窗 */}
      <PuzzleCaptcha 
        open={showCaptcha} 
        onSuccess={handleCaptchaSuccess} 
        onClose={handleCaptchaClose} 
      />
    </div>
  );
} 